#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
logging.basicConfig(level=logging.INFO)
import pdb
import sys
import  shutil 

'这个是冯秀伟专用的python工具库'
__author__='fengxw'


def copyfile(src , dst):
	shutil.copyfile(src ,dst);

def replace_in_file(old ,new , filepath):
	file_read = open(filepath , 'r');
	lines_read = [];
	for line_read in file_read:
		line_read = line_read.replace(old ,new)
		lines_read.append(line_read)
	file_read.close();

	file_write = open(filepath , 'w');
	for line_write in lines_read:
		file_write.write(line_write);
	file_write.close();

def find_dir(start_path , name):
	target=[]
	for root , dirs ,files in os.walk(start_path , topdown=False):
		for dir in dirs:
			if name == dir:
				target.append(os.path.join(root , dir))
#	logging.info(target)
	return target

def find_dir_father_path(start_path , name):
	target=[]
	for root , dirs ,files in os.walk(start_path , topdown=False):
		for dir in dirs:
			if name == dir:
				target.append(root)
	logging.info(target)
	return target


def cmd(runcmd):
	logging.info(runcmd)
	os.system(runcmd)

def clear(lists ,  key):
	def f(x): return x.find(key,0)==-1
	return filter(f , lists)

def all_git_path():
	lists=[]
	lists = find_dir_father_path(os.path.abspath('.'),'.git')
	lists = clear(lists , 'mxrepo')
	return lists

def run_cmd_on_all(real_cmd):
	lists = all_git_path()
	for path in lists:
		cmd('cd %s && %s ' % (path , real_cmd))

def checkout_all():
	run_cmd_on_all('git checkout .')

def create_branch_all(branch_name):
	run_cmd_on_all('git branch %s' % branch_name)

def create_tag_all(tag_name):
	run_cmd_on_all('git tag  %s' % tag_name)

def push_tag_all():
	run_cmd_on_all('git push --tags')
	
def pull_all():
	run_cmd_on_all('git pull')

def push_all_commit():
	run_cmd_on_all('git push ')

def switch_all_branch(to_branch):
	run_cmd_on_all('git checkout %s ' % to_branch)

def update_code():
	checkout_all()
	pull_all()

def show_all_git_origin():
	run_cmd_on_all('git remote show origin')

def show_all_git_branch():
	run_cmd_on_all('git branch')

#=================test code =================================================
if __name__=='__main__':
	logging.info('argv is:')
	logging.info(sys.argv)
	for i in range(len(sys.argv)):
		if sys.argv[i] == '-clear':
			checkout_all()
		elif sys.argv[i] == '-cb':
			create_branch_all(sys.argv[i+1])
		elif sys.argv[i] == '-ct':
			create_tag_all(sys.argv[i+1])
		elif sys.argv[i] == '-pt':
			push_tag_all()
		elif sys.argv[i] == '-pc':
			push_all_commit()
		elif sys.argv[i] == '-sb':
			switch_all_branch(sys.argv[i+1])
		elif sys.argv[i] == '-rpstr':
			replace_in_file(sys.argv[i+1] , sys.argv[i+2] , sys.argv[i+3])
		elif sys.argv[i] == '-cpy':
			copyfile(sys.argv[i+1] , sys.argv[i+2] )
		elif sys.argv[i] == '-pull':
			pull_all()
		elif sys.argv[i] == '-uc':#update code
			update_code()
		elif sys.argv[i] == '-show_origin':
			show_all_git_origin()
		elif sys.argv[i] == '-show_branch':
			show_all_git_branch()
	pass
